package cn.longg.controller;

import cn.longg.entity.Result;
import cn.longg.entity.User;
import cn.longg.service.IUserService;
import cn.longg.utils.IPUtil;
import com.alibaba.fastjson.JSON;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import java.util.Date;
import java.util.List;
import java.util.regex.Pattern;

import static cn.longg.utils.EncryptUtils.MD5_HEX;

@Controller
public class MainController {

    @Autowired
    private IUserService userService;

    @RequestMapping("toIndex")
    public String toLogin(){
        return "forward:index.html";
    }

    @RequestMapping("doLogin")
    @ResponseBody
    public Result doLogin(@RequestBody User user, HttpServletRequest request, HttpServletResponse response){
        String username = user.getUsername();
        String password = user.getPassword();
        String code = user.getLoginCode();
        boolean remember = user.getRemember();
        HttpSession session = request.getSession();
        if(null != code && !"".equals(code)){
            String realCode = (String) session.getAttribute("checkCode");
            if(code.equals(realCode)){
                if(null != username && !"".equals(username) && null != password && !"".equals(password)){
                    password = MD5_HEX(MD5_HEX(password) + username);
                    user.setPassword(password);
                    User checkUser = userService.selectOne(user);
                    if(null != checkUser){
                        int num = userService.getFansNum(checkUser.getId());
                        checkUser.setFansNum(num);
                        List<Integer> focusUser = userService.selectFocusUser(checkUser);
                        checkUser.setFocusUsers(focusUser);
                        session.setAttribute("loginUser",checkUser);
                        //记住我
                        if(remember){
                            String ipAddress = IPUtil.getIpAddress(request);
                            String jsonString = JSON.toJSONString(checkUser);
                            String key = ipAddress + checkUser.getUsername();
                            Cookie cookie = new Cookie("rememberKey",key);
                            cookie.setPath("/");
                            cookie.setMaxAge(60*60*24*7);
                            response.addCookie(cookie);
                            //将用户的json加到redis
                            userService.remember(key,jsonString);
                        }
                        checkUser.setLoginTime(new Date());
                        userService.updateByPrimaryKey(checkUser);
                        return new Result(true,"登录成功",checkUser);
                    }else {
                        return new Result(false,"账号或密码错误",null);
                    }
                }else {
                    return new Result(false,"账号密码不能为空",null);
                }
            }else {
                return new Result(false,"验证码错误",null);
            }
        }else {
            return new Result(false,"验证码不能为空",null);
        }
    }

    @RequestMapping("toHome")
    public ModelAndView toHome(){
        return new ModelAndView("home");
    }

    @RequestMapping("checkRegister")
    @ResponseBody
    public Result checkRegister(@RequestBody User user){
        int i = userService.checkRegister(user);
        if(i == 0){
            return new Result(true,"success",null);
        }
        return new Result(false,"fail",i);
    }

    @RequestMapping("doRegister")
    @ResponseBody
    public Result doRegister(@RequestBody User user){
        String username = user.getUsername();
        String email = user.getEmail();
        String password = user.getPassword();
        String password2 = user.getPassword2();
        if(null != username && !"".equals(username) && null != email && !"".equals(email) &&
                null != password && !"".equals(password) && null != password2 && !"".equals(password2)){
            int i = userService.checkRegister(user);
            if(0 == i){
                if(password.equals(password2)){
                    password = MD5_HEX(MD5_HEX(password) + username);
                    user.setPassword(password);
                    user.setRegisterTime(new Date());
                    user.setRealName("无名氏");
                    user.setDeptId(11);
                    user.setDeptName("无部门");
                    user.setIsSecret("1");
                    user.setPic("http://localhost:8080/upload/def.png");
                    int i1 = userService.doRegister(user);
                    if(0 < i1){
                        return new Result(true,"注册成功！",null);
                    }else{
                        return new Result(false,"注册失败！",null);
                    }
                }else {
                    return new Result(false,"两次输入密码不一致！",null);
                }
            }else {
                return new Result(false,"账号或邮箱已被注册！",null);
            }
        }else {
            return new Result(false,"所填信息不完整！",null);
        }
    }

    @RequestMapping("sidebar")
    public ModelAndView sidebar(){
        return new ModelAndView("sidebar");
    }

    @RequestMapping("navbar")
    public ModelAndView navbar(){
        return new ModelAndView("navbar");
    }

    @RequestMapping("logout")
    public String logout(HttpServletRequest request, HttpServletResponse response){
        HttpSession session = request.getSession();
        session.invalidate();
        Cookie[] cookies = request.getCookies();
        String key = null;
        if(null != cookies){
            for (Cookie cookie : cookies) {
                if("rememberKey".equals(cookie.getName())){
                    key = cookie.getValue();
                    cookie.setMaxAge(0);
                    cookie.setPath("/");
                    response.addCookie(cookie);
                }
            }
        }
        if(null != key){
            userService.delRemember(key);
        }

        return "redirect:index.html";
    }

    @RequestMapping("checkEmail")
    @ResponseBody
    public Result checkEmail(@RequestBody String email){
        email = email.replace("%40","@");
        email = email.replace("=","");
        boolean flag = userService.checkEmail(email);
        if(flag){
            return new Result(true,"存在该邮箱",null);
        }
        return new Result(false,"邮箱不存在",null);
    }

    @RequestMapping("code2Email")
    @ResponseBody
    public Result sendCode2Email(@RequestBody String email,HttpServletRequest request){
        email = email.replace("%40","@");
        email = email.replace("=","");
        String code = null;
        if(null != email){
            String regEx = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
            boolean matches = Pattern.matches(regEx, email);
            if(matches){
                boolean flag = userService.checkEmail(email);
                if(flag){
                    String ipAddress = IPUtil.getIpAddress(request);
                    String key = ipAddress + "emailCode";
                    code = userService.getEmailCode(key);
                    if(null != code && !"".equals(code)){
                        return new Result(false,"操作频繁！",null);
                    }else {
                        code = userService.sendEmailCode(email);
                        userService.setEmailCode(key,code);
                        return new Result(true,"发送成功，请注意查收",null);
                    }
                }else {
                    return new Result(false,"邮箱不存在",null);
                }
            }else {
                return new Result(false,"邮箱格式不对！",null);
            }
        }else {
            return new Result(false,"邮箱不能为空！",null);
        }

    }

    @RequestMapping("resetPassword")
    @ResponseBody
    public Result resetPassword(@RequestBody User user,HttpServletRequest request){
        String email = user.getEmail();
        String password = user.getPassword();
        String loginCode = user.getLoginCode();
        String ipAddress = IPUtil.getIpAddress(request);
        String key = ipAddress + "emailCode";
        String emailCode = userService.getEmailCode(key);

        if(null != emailCode && !"".equals(emailCode)){
            if(null != email && !"".equals(email) && null != password && !"".equals(password) &&
                    null != loginCode && !"".equals(loginCode)){
                if(emailCode.equals(loginCode)){
                    user.setPassword(null);
                    user = userService.selectOne(user);
                    password = MD5_HEX(MD5_HEX(password) + user.getUsername());
                    user.setPassword(password);
                    int i = userService.updateByPrimaryKey(user);
                    if(0 < i){
                        return new Result(true,"修改成功",null);
                    }else{
                        return new Result(false,"修改失败",null);
                    }
                }else {
                    return new Result(false,"验证码错误！",null);
                }
            }else {
                return new Result(false,"信息没有填写完整！",null);
            }
        }else {
            return new Result(false,"验证码已过期，请重新发送",null);
        }
    }




}
